﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using Common.Utilities;

namespace Workflows.Components.FileManipulation
{
    /// <summary>
    /// 
    /// </summary>
    public class FtpsClient
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="host"></param>
        /// <param name="sitePath"></param>
        /// <param name="srcFileName"></param>
        /// <param name="tgtFilePath"></param>
        /// <param name="userName"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public static bool Download(string host, string sitePath, string srcFileName, string tgtFilePath, string userName, string passWord)
        {
            bool suceed = false;
            Process proc=new Process();
            ProcessStartInfo startInfo=new ProcessStartInfo();
            string ftpsProgramFilePath =
                Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\FTPS", "FTPS.exe");
            startInfo.FileName = ftpsProgramFilePath;
            string scriptFilePath =
                Path.Combine(Path.GetDirectoryName(ftpsProgramFilePath),
                             Path.GetFileNameWithoutExtension(srcFileName) + ".ftps");
            CreateFtpScriptFile(scriptFilePath, sitePath, srcFileName, userName, passWord);
            string args = CreateFtpsArguments(host, Path.GetFileName(scriptFilePath));
            startInfo.Arguments = args;
            startInfo.UseShellExecute = false;
            startInfo.WorkingDirectory = Path.GetDirectoryName(ftpsProgramFilePath);
            try
            {
                proc.StartInfo = startInfo;
                proc.Start();
                proc.WaitForExit();

                string downloadedFilePath = Path.Combine(Path.GetDirectoryName(ftpsProgramFilePath), srcFileName);
                if (File.Exists(tgtFilePath))
                {
                    File.Move(downloadedFilePath, tgtFilePath);
                    suceed = true;
                }
            }
            catch(Exception ex)
            {
                ExceptionHandler.HandlesException(ex);
                suceed = false;
            }
            finally
            {
                if(File.Exists(scriptFilePath))
                {
                    File.Delete(scriptFilePath);
                }
            }
            return suceed;
        }

        private static void CreateFtpScriptFile(string scriptFilePath, string sitePath, string fileName, string userName, string password)
        {
            if(File.Exists(scriptFilePath))
            {
                File.Delete(scriptFilePath);
            }
            StreamWriter writer=new StreamWriter(scriptFilePath);
            // login 
            writer.WriteLine(userName);
            writer.WriteLine(password);
            // set passive
            writer.WriteLine("PASSIVE");
            // set private data connection
            writer.WriteLine("PROT P");
            writer.WriteLine("BINARY");
            // change ftp site path
            if(!string.IsNullOrEmpty(sitePath))
            {
                sitePath = sitePath.Replace("\\", "/");
                string[] subFolderNames = sitePath.Split(new char[] {'/'});
                foreach(string folderName in subFolderNames)
                {
                    writer.WriteLine("cd "+folderName);
                }
            }
            // get file
            writer.WriteLine("get \"{0}\"", fileName);
            writer.WriteLine("quit");
            writer.Flush();
            writer.Close();
        }

        private static string CreateFtpsArguments(string host, string scriptFileName)
        {
            StringBuilder buffer=new StringBuilder();
            buffer.Append(" -e:implicit");
            buffer.Append(" -z");
            buffer.Append(" " + host);
            buffer.Append(string.Format(" -s:\"{0}\"", scriptFileName));
            return buffer.ToString();
        }
    }
}
